今天的題單:
Convert Sorted Array to Binary Search Tree
Reverse Bits
要把已經排序好的 vector 做成 binary search tree,而且要 height-balanced。
思路:依照 binary search 作法,每次都並取區間內中間的值當作做成 node,這個中間的值會把區間分成兩半,這兩個分區的中間值將分別是 node 的左右節點,以此類推。
我使用遞迴方式實作。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return insert(0, nums.size()-1, nums);
}
TreeNode* insert(int begin, int end, vector<int>& nums) {
if (begin > end) return nullptr;
int mid = begin + (end - begin) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = insert(begin, mid-1, nums);
root->right = insert(mid+1, end, nums);
return root;
}
};
思路:先把 unsigned int 轉成 bitset,反轉完之後再轉成 unsigned int
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
bitset<32> binary(n);
for (int i = 0; i < 16; i++) {
if (binary[i] != binary[31-i]) {
// swap
binary[i] = !binary[i];
binary[31-i] = !binary[31-i];
}
}
return static_cast<uint32_t>(binary.to_ulong());
}
};